
#load data
Res=read.csv("ResPeerMain_ReSTAT.csv")

#new peer matrices, so as to ignore observations with no zip code
peermatrixsh2=peermatrix
peermatrixsh2[,is.na(Res$rskscr)]=0
peermatrixsh2[,is.na(peerdistmatrix[,1])]=0

# replace missing with zero (they are deleted from peermatrixsh2 so doesn't matter)
peerdistmatrix[is.na(peerdistmatrix)]=0

# replace missing values with zeros
Res$chscr[is.na(Res$chscr)]=0
Res$rskscr[is.na(Res$rskscr)]=0

#####################################################
# within 20
within20=matrix(as.numeric(peerdistmatrix<20),35536,35536)
peer20matrix=within20*peermatrixsh2
totday20=peer20matrix%*%ones
rm(ls="within20")

#build the measures
distance=data.frame(numzz=Res$numzz)
distance$peerrsk20=as.vector(peer20matrix %*% Res$rskscr / totday20)
distance$peerch20=as.vector(peer20matrix %*% Res$chscr / totday20)
# make the percent within 20 variable
distance$perc20=as.vector(totday20/totdaysh)

head(distance)
write.dta(distance, file="distance_ReSTAT.dta")

